package com.hljcert.data.service.system.service;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.hljcert.data.service.common.config.SystemProperties;
import com.hljcert.data.service.common.result.Result;
import com.hljcert.data.service.common.util.PasswordUtil;
import com.hljcert.data.service.system.dto.LoginDTO;
import com.hljcert.data.service.system.entity.SysUser;
import com.hljcert.data.service.system.vo.LoginVO;
import com.hljcert.data.service.system.vo.UserInfoVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AuthService {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SystemProperties systemConfig;

    /**
     * 用户登录
     * @param dto
     * @return
     */
    public Result<LoginVO> login(LoginDTO dto){
        if (StringUtils.isBlank(dto.getUserName()) || StringUtils.isBlank(dto.getPassword())) {
            return Result.error("账号或密码不能为空!");
        }

        SysUser user = this.sysUserService.getAdminByLoginName(dto.getUserName());
        if (user == null){
            return Result.error("账号或密码错误!");
        }

        // 验证密码
        String encryptPwd = PasswordUtil.encrypt(dto.getUserName(), dto.getPassword(), systemConfig.getAdminSecretKey());
        if (!user.getPassword().equals(encryptPwd)) {
            return Result.error("账号或密码错误!");
        }
        return Result.OK(loginAndInitSession(user));
    }


    /**
     * 登录并初始化session
     * @return
     */
    private LoginVO loginAndInitSession(SysUser user){
        StpUtil.login(user.getId());
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        // 设置session
        StpUtil.getSession().set("user_info", user);
        LoginVO loginVO = new LoginVO();
        loginVO.setTokenName(tokenInfo.getTokenName());
        loginVO.setAccessToken(tokenInfo.getTokenValue());
        loginVO.setUserInfo(new UserInfoVO(user.getId(), user.getName(), user.getLoginName()));
        return loginVO;
    }
}
